/**
 *  JSimProd - Java simulation code for production processes
 *  Copyleft Jorge Mira Yagüe <jorge.mira.yague@gmail.com>
 *  Universidad de Alicante 2009
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

/*
 * frmItemCategroy.java
 *
 * Created on 12-feb-2009, 13:01:04
 */
package gui.forms;

import gui.tools.Receiver;
import gui.tools.models.TMDistribution;
import java.awt.Image;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.swing.JOptionPane;
import javax.swing.event.TableModelEvent;
import lib.model.FactoryModel;
import lib.model.ItemCategory;
import lib.model.Task;
import lib.model.distribution.Distribution;
import lib.plan.Item;
import lib.plan.Order;

/**
 *
 * @author jorge
 */
public class FrmItem extends javax.swing.JDialog implements Receiver {

    private Item item = null;
    private FactoryModel factory;
    private Order order;
    private int index;
    private Receiver parent;

    public FrmItem(Item item, Order order, FactoryModel factory, Receiver parent) {
        initComponents();

        this.getRootPane().setDefaultButton(btnSave);

        tbParameters.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {
                    btnEditActionPerformed(null);
                }
            }
        });

        String fileString = "/res/icons/logo.png";
        try {
            Image icon = ImageIO.read(getClass().getResource(fileString));
            this.setIconImage(icon);
        } catch (java.io.IOException ioe) {
            System.out.println("Error loading file: " + fileString);
        }

        this.item = item;
        this.order = order;
        this.factory = factory;
        this.parent = parent;


        for (ItemCategory ic : factory.getItemCategories().values()) {
            cbCategory.addItem(ic.getName());
        }
        if (item == null) {
            this.setTitle("New item");
            if (order != null) {
                txtPriority.setText(String.valueOf(this.order.getPriority()));
            }
        } else {
            this.setTitle("Editing item: " + String.valueOf(item.getNumber()));
            txtNumber.setText(String.valueOf(item.getNumber()));
            txtPriority.setText(String.valueOf(item.getPriority()));
            cbCategory.setSelectedItem(item.getCategory());
        }

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnCancel = new javax.swing.JButton();
        btnSave = new javax.swing.JButton();
        lblPriority = new javax.swing.JLabel();
        lblCategory = new javax.swing.JLabel();
        txtPriority = new javax.swing.JTextField();
        cbCategory = new javax.swing.JComboBox();
        lblParameters = new javax.swing.JLabel();
        btnEdit = new javax.swing.JButton();
        spParameters = new javax.swing.JScrollPane();
        tbParameters = new javax.swing.JTable();
        lblNumber = new javax.swing.JLabel();
        txtNumber = new javax.swing.JTextField();

        setModal(true);
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        btnCancel.setText("Cancel");
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        btnSave.setText("Save");
        btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveActionPerformed(evt);
            }
        });

        lblPriority.setText("Priority:");

        lblCategory.setText("Category:");

        cbCategory.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbCategoryActionPerformed(evt);
            }
        });

        lblParameters.setText("Parameters:");

        btnEdit.setText("Edit...");
        btnEdit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditActionPerformed(evt);
            }
        });

        tbParameters.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        spParameters.setViewportView(tbParameters);

        lblNumber.setText("Number:");
        lblNumber.setEnabled(false);

        txtNumber.setEnabled(false);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(spParameters, javax.swing.GroupLayout.DEFAULT_SIZE, 389, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(lblNumber)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(txtNumber, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblCategory)
                            .addComponent(lblPriority))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtPriority, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(cbCategory, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(lblParameters)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 250, Short.MAX_VALUE)
                        .addComponent(btnEdit))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnSave)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnCancel)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblNumber)
                    .addComponent(txtNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblPriority)
                    .addComponent(txtPriority, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(10, 10, 10)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblCategory)
                    .addComponent(cbCategory, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblParameters)
                    .addComponent(btnEdit))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(spParameters, javax.swing.GroupLayout.PREFERRED_SIZE, 272, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnCancel)
                    .addComponent(btnSave))
                .addContainerGap())
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-417)/2, (screenSize.height-497)/2, 417, 497);
    }// </editor-fold>//GEN-END:initComponents

    private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed

        if (txtPriority.getText().equals("")) {
            txtPriority.setText("0");
        }
        int priority = Integer.parseInt(txtPriority.getText());
        if (order == null && priority < 0) {
            JOptionPane.showMessageDialog(rootPane,
                    "Error:\n Priority must be bigger than zero.",
                    "Error",
                    JOptionPane.ERROR_MESSAGE);
        } else {
            priority = priority > 0 ? priority : order.getPriority();
            item = new Item(cbCategory.getSelectedItem().toString(),
                    priority,
                    ((TMDistribution) tbParameters.getModel()).getDistributions());
            if (!txtNumber.getText().equals("")) {
                item.setNumber(Integer.parseInt(txtNumber.getText()));
            }
            parent.reciveObject(item);
            this.setVisible(false);
        }
    }//GEN-LAST:event_btnSaveActionPerformed

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        this.setVisible(false);
    }//GEN-LAST:event_btnCancelActionPerformed

    private void btnEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditActionPerformed
        index = tbParameters.getSelectedRow();
        if (index >= 0) {
            TMDistribution tmd = (TMDistribution) tbParameters.getModel();
            new FrmDistrubution(tmd.getDistrubution(index), this).setVisible(true);
        } else {
            JOptionPane.showMessageDialog(rootPane,
                    "Error:\n Please select a parameter.",
                    "Error",
                    JOptionPane.ERROR_MESSAGE);
            return;
        }
    }//GEN-LAST:event_btnEditActionPerformed

    private void cbCategoryActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbCategoryActionPerformed
        String ICName = (String) cbCategory.getSelectedItem();
        List<Distribution> dists = new ArrayList<Distribution>();
        List<Task> tasks;
        tasks = factory.getItemCategories().get(ICName).getTasks();
        for (Task t : tasks) {
            dists.add(t.getDistribution());
        }
        tbParameters.setModel(new TMDistribution(dists));
    }//GEN-LAST:event_cbCategoryActionPerformed

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
    }//GEN-LAST:event_formWindowClosed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
    }//GEN-LAST:event_formWindowClosing
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnEdit;
    private javax.swing.JButton btnSave;
    private javax.swing.JComboBox cbCategory;
    private javax.swing.JLabel lblCategory;
    private javax.swing.JLabel lblNumber;
    private javax.swing.JLabel lblParameters;
    private javax.swing.JLabel lblPriority;
    private javax.swing.JScrollPane spParameters;
    private javax.swing.JTable tbParameters;
    private javax.swing.JTextField txtNumber;
    private javax.swing.JTextField txtPriority;
    // End of variables declaration//GEN-END:variables

    public void reciveObject(Object object) {
        Distribution dist = (Distribution) object;
        TMDistribution tmd = (TMDistribution) tbParameters.getModel();
        tmd.setDistribution(index, dist);
        tbParameters.setModel(tmd);
        tbParameters.tableChanged(new TableModelEvent(tbParameters.getModel()));
    }
}
